/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package work.lock.reentrantLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
 * @author Sakura Shen
 * @description ReentrantLock实现锁机制
 * @date 2021/9/22
 */
@Slf4j
public class ReentrantLockTest1 {

    private Lock lock = new ReentrantLock();

    public void testMethod(){
        try {
            System.out.println(StrUtil.format("threadName -> {} enter testMethod",Thread.currentThread().getName()));

            // 加锁
            lock.lock();
            System.out.println(StrUtil.format("threadName -> {} lock",Thread.currentThread().getName()));
            Thread.sleep(2*1000);
            System.out.println(StrUtil.format("threadName -> {} unlock",Thread.currentThread().getName()));

            // 释放锁
            lock.unlock();
            System.out.println(StrUtil.format("threadName -> {} exit testMethod",Thread.currentThread().getName()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        final ReentrantLockTest1 demo1 = new ReentrantLockTest1();

        // 两个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                demo1.testMethod();
            }
        },"threadA").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                demo1.testMethod();
            }
        },"threadB").start();
    }
}
